package com.swpu.service_sleep.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swpu.service_sleep.entity.SleepRecord;
import com.swpu.service_sleep.entity.SleepRecordVo;
import com.swpu.service_sleep.entity.SleepVo;
import com.swpu.service_sleep.mapper.SleepRecordMapper;
import com.swpu.service_sleep.service.SleepRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chaichai
 * @since 2024-02-18
 */
@Service
public class SleepRecordServiceImpl extends ServiceImpl<SleepRecordMapper, SleepRecord> implements SleepRecordService {

    @Override
    public void saveUserSleepData(SleepRecord sleepRecord, String openid) {
        LambdaQueryWrapper<SleepRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SleepRecord::getUserId,openid).between(SleepRecord::getEndTime, DateUtil.beginOfDay(sleepRecord.getEndTime()),DateUtil.endOfDay(sleepRecord.getEndTime()));
        SleepRecord record = this.getOne(queryWrapper);
        if (record!=null){
            record.setEndTime(sleepRecord.getEndTime());
            record.setStartTime(sleepRecord.getStartTime());
            this.updateById(record);
        }else {
            sleepRecord.setUserId(openid);
            sleepRecord.setRecordTime(new Date());
            boolean isSave = this.save(sleepRecord);
            if (!isSave) throw new RuntimeException("保存用户数据失败");
        }

    }

    @Override
    public List<SleepVo> getUserMonthData(String openid, String dayStr) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = format.parse(dayStr);
        } catch (ParseException e) {
            throw new RuntimeException();
        }
        LambdaQueryWrapper<SleepRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SleepRecord::getUserId,openid).between(SleepRecord::getEndTime,DateUtil.beginOfMonth(date),DateUtil.endOfMonth(date));
        List<SleepRecord> sleepRecords = this.list(queryWrapper);
        DecimalFormat df = new DecimalFormat("#.0");
        ArrayList<SleepVo> sleepVos = new ArrayList<>();
        for (SleepRecord sleepRecord : sleepRecords) {
            SleepVo sleepVo = new SleepVo();
            sleepVo.setEndTime(sleepRecord.getEndTime());
            sleepVo.setDate(sleepRecord.getEndTime());
            sleepVo.setStartTime(sleepRecord.getStartTime());
            //计算时间间隔
            long timeDiff= sleepRecord.getEndTime().getTime()-sleepRecord.getStartTime().getTime();
            Double duration_hour= Double.valueOf((double)timeDiff /(3600*1000));
            String duration = df.format(duration_hour);
            sleepVo.setDuration(duration);
            sleepVos.add(sleepVo);
        }
        return sleepVos;
    }

    @Override
    public SleepRecordVo getUserSleepChartData(String openid, Integer page, Integer pageSize) {
        DecimalFormat df = new DecimalFormat("#.0");
        LambdaQueryWrapper<SleepRecord> queryWrapper = new LambdaQueryWrapper<>();
        Page<SleepRecord> recordPage = new Page<>(page,pageSize);
        queryWrapper.eq(SleepRecord::getUserId,openid).orderByDesc(SleepRecord::getStartTime);
        this.page(recordPage,queryWrapper);
        List<SleepRecord> records = recordPage.getRecords();
        double avgHour = 0.0;
        for (SleepRecord record : records) {
            //计算时间间隔
            long timeDiff= record.getEndTime().getTime()-record.getStartTime().getTime();
            Double duration_hour= Double.valueOf((double)timeDiff /(3600*1000));
            avgHour+=duration_hour;
            String duration = df.format(duration_hour);
            record.setDuration(duration);
        }
        SleepRecordVo sleepRecordVo = new SleepRecordVo();
        sleepRecordVo.setAvgSleepHour(Double.valueOf(df.format(avgHour/records.size())));
        records.sort(Comparator.comparing(SleepRecord::getRecordTime));
        sleepRecordVo.setSleepRecordList(records);
        String hourTime = this.getSleepStartAvgHour(records);
        sleepRecordVo.setStartSleepHourTime(hourTime);
        return sleepRecordVo;
    }

    @Override
    public Double getAvgSleepHour(String openid, Integer days) {
        DecimalFormat df = new DecimalFormat("#.0");
        LambdaQueryWrapper<SleepRecord> queryWrapper = new LambdaQueryWrapper<>();
        Page<SleepRecord> recordPage = new Page<>(1,days);
        queryWrapper.eq(SleepRecord::getUserId,openid).orderByDesc(SleepRecord::getStartTime);
        this.page(recordPage,queryWrapper);
        double avgHour = 0.0;
        List<SleepRecord> records = recordPage.getRecords();
        for (SleepRecord record : records) {
            //计算时间间隔
            long timeDiff= record.getEndTime().getTime()-record.getStartTime().getTime();
            Double duration_hour= Double.valueOf((double)timeDiff /(3600*1000));
            avgHour+=duration_hour;
        }
       return Double.valueOf(df.format(avgHour/records.size()));
    }

    public String getSleepStartAvgHour(List<SleepRecord> records){
        int hours = 0;
        int minutes=0;
        for (int i = 0; i < records.size(); i++) {
            Date startTime = records.get(i).getStartTime();
            hours += startTime.getHours();
             minutes+= startTime.getMinutes();
        }
        minutes+=hours*60;
        return (minutes/records.size())/60+":"+(minutes/ records.size())%60;
    }
}
